import React, { useRef, useEffect, useState } from "react";
import io from "socket.io-client";

const SIGNAL_SERVER_URL = "http://localhost:3001"; // 信令服务器地址
let pc = null;

export default function Tlist() {
  const localVideo = useRef(null);
  const remoteVideo = useRef(null);
  const socketRef = useRef(null);
  const [incomingCall, setIncomingCall] = useState(false);
  const [callAccepted, setCallAccepted] = useState(false);

  useEffect(() => {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
      localVideo.current.srcObject = stream;
      pc = new RTCPeerConnection();
      stream.getTracks().forEach(track => pc.addTrack(track, stream));
      pc.ontrack = (event) => {
        remoteVideo.current.srcObject = event.streams[0];
      };
      socketRef.current = io(SIGNAL_SERVER_URL);
      socketRef.current.on("signal", async (data) => {
        if (data.type === "call") {
          // 收到呼叫请求，显示接听按钮
          setIncomingCall(true);
        } else if (data.type === "offer") {
          setCallAccepted(true);
          setIncomingCall(false);
          await pc.setRemoteDescription(new RTCSessionDescription(data.offer));
          const answer = await pc.createAnswer();
          await pc.setLocalDescription(answer);
          socketRef.current.emit("signal", { type: "answer", answer });
        } else if (data.type === "candidate") {
          try {
            await pc.addIceCandidate(new RTCIceCandidate(data.candidate));
          } catch (e) {}
        }
      });
      pc.onicecandidate = (event) => {
        if (event.candidate) {
          socketRef.current.emit("signal", { type: "candidate", candidate: event.candidate });
        }
      };
    });
    return () => {
      if (socketRef.current) socketRef.current.disconnect();
      if (pc) pc.close();
    };
  }, []);

  // 接听来电
  const acceptCall = () => {
    setCallAccepted(true);
    setIncomingCall(false);
    socketRef.current.emit("signal", { type: "accept" });
  };

  return (
    <div style={{ position: "relative", width: "100vw", height: "100vh", background: "#000" }}>
      {/* 大窗口：对方画面 */}
      <video
        ref={remoteVideo}
        autoPlay
        playsInline
        style={{
          width: "100vw",
          height: "100vh",
          objectFit: "cover",
          background: "#222"
        }}
      />
      {/* 小窗口：自己画面 */}
      <video
        ref={localVideo}
        autoPlay
        playsInline
        muted
        style={{
          position: "absolute",
          right: 20,
          bottom: 20,
          width: 180,
          height: 120,
          borderRadius: 8,
          boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
          background: "#444"
        }}
      />
      {/* 接听按钮 */}
      {incomingCall && !callAccepted && (
        <button
          onClick={acceptCall}
          style={{
            position: "absolute",
            left: 20,
            bottom: 20,
            zIndex: 10
          }}
        >
          接听
        </button>
      )}
    </div>
  );
}